<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入账户名称"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建" type="primary" icon="el-icon-plus" size="medium" perms="PT_USER_ADD"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        border
        style="width: 100%;"
        class="elTable"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="userName" label="账户名称" align="center"/>
        <el-table-column prop="userPhone" label="手机号" align="center"/>
        <el-table-column prop="projectRoleName" label="客户角色" align="center"/>
        <el-table-column prop="isFirst" label="是否为初始密码" align="center" width="130">
          <template slot-scope="{ row }">
            <span v-if="row.isFirst == 'Y'">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column prop="createByName" label="创建人" align="center"/>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column prop="updateByName" label="更新人" align="center"/>
        <el-table-column label="更新时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="{ row }">
            <perButton label="分配控制" type="primary" size="mini" perms="PT_USER_EDIT"
                       @click="configControl(row)"></perButton>
            <perButton label="重置密码" type="danger" size="mini"
                       perms="PT_USER_RESTPWD" @click="handlerReset(row)"></perButton>
            <perButton label="编辑" type="warning" size="mini" perms="PT_USER_EDIT"
                       @click="handlerEdit(row)"></perButton>
            <perButton label="删除" type="danger" size="mini" perms="PT_USER_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 新建 -->
    <yc-dialog ref="ycDialog" :dialogTitle="dialogTitle" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="newAccountFormRef"
            :rules="newAccountModelRules"
            :model="newAccountModel"
            :disabled="detailsDisabled"
            label-width="90px"
          >
            <el-form-item label="账户名称" prop="userName">
              <el-input v-model="newAccountModel.userName"/>
            </el-form-item>
            <el-form-item label="手机号码" prop="userPhone">
              <el-input type="number" v-model="newAccountModel.userPhone"/>
            </el-form-item>
            <el-form-item label="客户角色" prop="projectRoleCode">
              <el-select v-model="newAccountModel.projectRoleCode" class="w-100">
                <el-option
                  v-for="item in roleData"
                  :key="item.projectRoleCode"
                  :label="item.projectRoleName"
                  :value="item.projectRoleCode"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 分配控制 -->
    <yc-dialog ref="configDialog" :dialogTitle="dialogTitle" :show-center="false" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="newConfigFormRef"
            :rules="newConfigModelRules"
            :model="newConfigModel"
            :disabled="detailsDisabled"
            label-width="90px"
          >
            <el-form-item label="控制标签" prop="childCodeList">
              <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                           @change="handleCheckAllChange">全选
              </el-checkbox>
              <el-checkbox-group v-model="newConfigModel.childCodeList" @change="checkGroupChange">
                <div v-for="item in checkDataList" :key="item.tagCode">
                  <el-checkbox :label="item.tagCode">{{item.tagName}}</el-checkbox>
                </div>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="configDialogSave">确定</el-button>
        <el-button @click="$refs.configDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"

  import {
    queryPage,
    insertByModel,
    updateByModel,
    deleteByModel,
    resetPassword
  } from "@/api/projectBasicsSetup/accountManage"
  import {
    queryList
  } from "@/api/projectBasicsSetup/roleManage"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        isGlobalMessageShow: false,
        message: "",

        projectCode: "",
        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 10,
        loading: false,

        roleData: [],

        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },

        newAccountModel: {
          userName: "",
          userPhone: "",
          projectRoleCode: "",
          id: 0
        },
        newAccountModelRules: {
          userName: [{required: true, message: "请输入账户名称", trigger: "blur"}],
          userPhone: [{required: true, message: "请输入手机号码", trigger: "blur"}],
          projectRoleCode: [{required: true, message: "请选择客户角色", trigger: "change"}],
        },

        dialogTitle: "",
        centerTitle: "",

        newConfigModel: {
          userCode: "",
          roleCode: "",
          childCodeList: []
        },
        newConfigModelRules: {
          childCodeList: [
            {type: 'array', required: true, message: "请选择控制标签", trigger: "change"}
          ],
        },
        checkDataList: [],
        checkAll: false,
        isIndeterminate: false,

        detailsDisabled: false,
        addOrUpdateLoading: false
      }
    },
    created() {
      this.projectCode = sessionStorage.getItem('projectCode')
      this.getAccountData()
    },
    methods: {
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const {userName, status} = tableInfo
          const {object} = await queryPage({
            projectCode: this.projectCode,
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const {object} = await queryPage({
            projectCode: this.projectCode,
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },
      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },

      /**
       * 删除按钮
       */
      async handlerDelete({id}) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {message, status} = await deleteByModel({id})
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      /**
       * 重置按钮
       */
      async handlerReset({id}) {
        this.$confirm("确定重置密码吗", "重置操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        }).then(async () => {
          const {message, status} = await resetPassword({id})
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },


      /**
       * 新建
       * */
      async handlerAccount() {
        this.dialogTitle = "添加"
        this.centerTitle = "添加"

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true

        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
        await this.queryList()
      },

      /**
       * 修改
       */
      async handlerEdit(row) {
        this.dialogTitle = "编辑"
        this.centerTitle = "编辑"

        this.newAccountModel.id = row.id
        this.newAccountModel.userName = row.userName
        this.newAccountModel.userPhone = row.userPhone
        this.newAccountModel.projectRoleCode = row.projectRoleCode

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true

        await this.queryList()
      },

      async queryList() {
        const {object} = await queryList({
          projectCode: this.projectCode
        })
        this.roleData = object
      },

      dialogSave() {
        this.$refs.newAccountFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newAccountModel.id) {
              const {message, status} = await updateByModel({
                projectCode: this.projectCode,
                ...this.newAccountModel
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            } else {
              const {message, status} = await insertByModel({
                projectCode: this.projectCode,
                ...this.newAccountModel
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },


      // 分配控制
      async configControl(row) {
        this.dialogTitle = "分配控制"
        this.centerTitle = "分配控制"

        this.newConfigModel.userCode = row.userCode
        this.newConfigModel.roleCode = row.roleCode
        // this.newConfigModel.childCodeList = row.tagCode ? row.tagCode.split("&") : []
        if(row.tagCode) {
          let value = row.tagCode.split("&")

          this.newConfigModel.childCodeList = value

          let checkedCount = value.length
          this.checkAll = checkedCount === this.checkDataList.length
          this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkDataList.length
        } else {
          this.checkAll = false
          this.isIndeterminate = false
          this.newConfigModel.childCodeList = []
        }

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.configDialog.dialogVisible = true
        await this.queryTagListByRoleCode()
      },
      async queryTagListByRoleCode() {
        const {object} = await queryTagListByRoleCode({
          roleCode: this.newConfigModel.roleCode
        })
        this.checkDataList = object
      },
      // 全选
      handleCheckAllChange(val) {
        this.newConfigModel.childCodeList = val ? this.checkDataList.map(item => item.tagCode) : []
        this.isIndeterminate = false
      },
      checkGroupChange(value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.checkDataList.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkDataList.length
      },
      configDialogSave() {
        this.$refs.newConfigFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            const {userCode, childCodeList} = this.newConfigModel
            const {message, status} = await setTagByAccount({
              userCode,
              tagCode: childCodeList.join('&')
            })
            if (status == 200) {
              this.getAccountData()
              this.$refs.configDialog.dialogVisible = false
              this.$message.success(message)
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }



  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
